<template>
  <!-- 注册功能
         1：定义对应模块的api.js
         2:定义注册接口调用的api方法
         3：在注册页面导入api方法
         4：在点击注册表单验证通过后调用注册api方法
         5：注册成功
             提示一下
             同时跳转到登陆页  -->

  <div class="register">
    <van-nav-bar title="面经注册"></van-nav-bar>
    <!-- 表单验证
        1：van-form包住表单元素
        2：van-field 绑定rules
        3:通过ref调用form组件内的validate方法
    -->
    <van-form ref="form">
      <van-field
        label="用户名"
        v-model="form.username"
        placeholder="用户名"
        :rules="rules.username"
      ></van-field>
      <van-field
        label="密码"
        v-model="form.password"
        placeholder="密码"
        :rules="rules.password"
        type="password"
      ></van-field>
    </van-form>
    <div class="bottom">
      <van-button block color="#07c160" @click="submit">注册</van-button>
      <p class="right">
        <router-link to="/login">有帐号,去登陆</router-link>
      </p>
    </div>
  </div>
</template>
<script>
import { userRegister } from '@/api/user.js'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'onChange' },
          {
            pattern: /^\w{4,12}$/,
            message: '请输入4-12位字符',
            trigger: 'onChange'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'onChange' },
          {
            pattern: /^\w{6,12}$/,
            message: '请输入6-12位字符',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form
        .validate()
        .then(async () => {
          console.log('验证成功')
          // try {
          await userRegister(this.form)
          // 注册成功要提示
          // console.log(res)
          this.$toast.success('注册成功')
          // 跳转到登陆页
          this.$router.push('/login')
          // } catch (err) {
          //   console.log('1111', err)
          //   this.$toast.fail(err.response.data.message)
          // }
        })
        .catch(() => {
          console.log('验证失败')
        })
    }
  }
}
</script>
<style lang="less" scoped>
.register {
  .bottom {
    padding: 15px 15px 0;
    .right {
      text-align: right;
    }
  }
}
</style>
